package com.demo.ribbon.client.custom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @GetMapping("/hi")
    public String hi(@RequestParam(value = "name", defaultValue = "hi") String name) {
        String hello = restTemplate.getForObject("http://hi-hello/hello", String.class);
        return String.format("%s,%s", hello, name);
    }


    @GetMapping("/his")
    public String his(@RequestParam(value = "name", defaultValue = "Y") String name) {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("hi-hello");
        System.out.println("111" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + ":" + serviceInstance.getServiceId());
        String url = String.format("http://%s:%s/%s?name=%s", serviceInstance.getHost(), serviceInstance.getPort(), "hello", name);
        System.out.println(url);
        URI storesUri = URI.create(url);
        String hello = restTemplate.getForObject(storesUri, String.class);
        return hello;
    }


}
